import os
import time

from alipay.util import create_directory_if_not_exists, get_time, calculate_image_similarity


class AppiumUtils:
    driver = None
    logger = None

    def __init__(self, driver, logger):
        self.driver = driver
        self.logger = logger

    def swipe_to_bottom_for_screen(self, work_path, dst_folder, is_img_resource=False):
        """
        滚动截屏
        :param work_path: 工作空间
        :param dst_folder: 滚动截屏后存放图片的子文件夹
        :param is_img_resource: 如果是图片，则计算相似度， 否则 看文本内容是否一致
        :return:
        """
        sub_folder_path = os.path.join(work_path, dst_folder)
        create_directory_if_not_exists(sub_folder_path)
        self.logger.info(f'start swipe_to_bottom_for_screen')
        num = 0
        ##  等待页面加载完成
        time.sleep(2)
        while True:
            num = num + 1
            self.driver.save_screenshot(f'{sub_folder_path}/{dst_folder}_{num}_screenshot.png')
            # 获取滑动前页面元素
            before_swipe = self.driver.page_source
            before_swipe_png = self.driver.get_screenshot_as_png()
            self.swipe_up(self.driver)
            # 获取滑动后页面元素
            after_swipe = self.driver.page_source
            after_swipe_png = self.driver.get_screenshot_as_png()
            ##  计算图片相似度
            similarity = calculate_image_similarity(before_swipe_png, after_swipe_png, False)
            self.logger.info(f"calculate_image_similarity {similarity}")
            is_bottom = (before_swipe == after_swipe) if not is_img_resource else \
                calculate_image_similarity(before_swipe_png, after_swipe_png, False) > 0.9
            # 对比滑动前后的页面元素
            # 若滑动前后页面元素完全相同，则滑动失败，已达页尾
            if is_bottom:
                swip_finished = True
                # 若滑动前后页面元素不同，则滑动成功，继续滑动
            else:
                swip_finished = False
            self.logger.info(f"swip_finished {swip_finished}")
            if swip_finished:
                break

    # 获取手机屏幕尺寸
    def get_size(self, driver):
        x = driver.get_window_size()['width']
        y = driver.get_window_size()['height']
        return (x, y)

    def swip_header_fast(self, driver):
        while True:
            # 获取滑动前页面元素
            before_swipe = driver.page_source
            self.swipe_down(driver, 0)
            # 获取滑动后页面元素
            after_swipe = driver.page_source
            # 对比滑动前后的页面元素
            # 若滑动前后页面元素完全相同，则滑动失败，已达页尾
            if before_swipe == after_swipe:
                swip_finished = True
                # 若滑动前后页面元素不同，则滑动成功，继续滑动
            else:
                swip_finished = False
            print(f"swip_finished {swip_finished}")
            if swip_finished:
                break

    # 屏幕向上滑动（从中间位置，由下往上滑，比例可以自己调节）
    @get_time
    def swipe_up(self, driver):
        l = self.get_size(driver)
        x1 = int(l[0] * 0.5)  # x坐标
        y1 = int(l[1] * 0.8)  # 起始y坐标
        y2 = int(l[1] * 0.2)  # 终点y坐标
        driver.swipe(x1, y1, x1, y2, 2000)

    # 屏幕向下滑动（从中间位置，由上往下滑，比例可以自己调节）
    def swipe_down(self, driver):
        self.swipe_down(driver, 200)

    def swipe_down(self, driver, duration: int = 0):
        l = self.get_size(driver)
        x1 = int(l[0] * 0.5)  # x坐标
        y1 = int(l[1] * 0.45)  # 起始y坐标
        y2 = int(l[1] * 0.8)  # 终点y坐标
        driver.swipe(x1, y1, x1, y2, 200)

    # 屏幕向左滑动（从中间位置，由右往左滑，比例可以自己调节）
    def swipe_left(self, driver):
        # 记录开始时间
        l = self.get_size(driver)
        x1 = int(l[0] * 0.9)  # 起始x坐标
        x2 = int(l[0] * 0.1)  # 终点x坐标
        y1 = int(l[1] * 0.5)  # y坐标
        driver.swipe(x1, y1, x2, y1, 1000)
        # 记录结束时间

    # 屏幕向右滑动（从中间位置，由左往右滑，比例可以自己调节）
    def swipe_right(self, driver):
        l = self.get_size(driver)
        x1 = int(l[0] * 0.1)  # 起始x坐标
        x2 = int(l[0] * 0.9)  # 终点x坐标
        y1 = int(l[1] * 0.5)  # y坐标
        driver.swipe(x1, y1, x2, y1, 1000)

    def swipe_right(self, driver, y):
        """
        在指定的y区域向右滑动
        :param driver:
        :param y:
        :return:
        """
        l = self.get_size(driver)
        x1 = int(l[0] * 0.1)  # 起始x坐标
        x2 = int(l[0] * 0.9)  # 终点x坐标
        y1 = y
        driver.swipe(x1, y1, x2, y1, 1000)
